import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:zhibao_flutter/api/wallet/wallet_entity.dart';
import 'package:zhibao_flutter/api/wallet/wallet_view_model.dart';
import 'package:zhibao_flutter/util/data/page_mini.dart';
import 'package:zhibao_flutter/util/func/smart_refresh.dart';
import 'package:zhibao_flutter/widget/appbar/commom_bar.dart';
import 'package:zhibao_flutter/widget/base/my_scaffold.dart';
import 'package:zhibao_flutter/widget/data/loading_view.dart';
import 'package:zhibao_flutter/widget/data/no_data_view.dart';
import 'package:zhibao_flutter/zone.dart';

import 'bill_logic.dart';

class BillPage extends StatefulWidget {
  @override
  State<BillPage> createState() => _BillPageState();
}

class BillConfig {
  static String useParamKey = "BillTypeFromEnum";
}

class _BillPageState extends State<BillPage> with TickerProviderStateMixin {
  final logic = Get.find<BillLogic>();

  @override
  void initState() {
    super.initState();
    int initIndex = 0;
    if (Get.arguments is Map &&
        (Get.arguments as Map).containsKey(BillConfig.useParamKey) &&
        Get.arguments[BillConfig.useParamKey] is BillTypeFromEnum) {
      initIndex = logic.tabs.indexWhere((element) =>
          element.billType == Get.arguments[BillConfig.useParamKey]);
      logic.tabC = TabController(
        length: logic.tabs.length,
        vsync: this,
        initialIndex: initIndex,
      );
    }
    logic.tabC = TabController(
      length: logic.tabs.length,
      vsync: this,
      initialIndex: initIndex,
    );
  }

  @override
  Widget build(BuildContext context) {
    return MyScaffold(
      appBar: CommomBar(
        title: "assetDetails".tr,
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(height: (29 - 16.px).px),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 30.px),
            // child: Text(
            // '明细',
            // style: TextStyle(
            //     color: Color(0xff000000),
            //     fontSize: 14.px,
            //     fontWeight: MyFontWeight.semBold),
            // ),
          ),
          SizedBox(height: 9.px),
          TabBar(
            controller: logic.tabC,
            isScrollable: true,
            tabAlignment: TabAlignment.start,
            labelStyle: TextStyle(fontWeight: MyFontWeight.semBold),
            unselectedLabelStyle: TextStyle(fontWeight: MyFontWeight.medium),
            tabs: logic.tabs.map((e) {
              return Tab(text: e.title);
            }).toList(),
          ),
          Expanded(
            child: TabBarView(
              controller: logic.tabC,
              children: logic.tabs.map((e) {
                return BillTabPage(e);
              }).toList(),
            ),
          )
        ],
      ),
    );
  }
}

class BillTabPage extends StatefulWidget {
  final BillTabModel model;

  BillTabPage(this.model);

  @override
  State<BillTabPage> createState() => _BillTabPageState();
}

class _BillTabPageState extends State<BillTabPage> with PageMiniAbs, PageMini {
  static TextStyle hintStyle = TextStyle(
    color: Color(0xff999999),
    fontSize: 12.px,
    fontWeight: MyFontWeight.medium,
  );

  List<WalletRspEntity> dataList = [];

  @override
  void initState() {
    super.initState();
    refreshHandle();
  }

  Future getData() async {
    final value = await walletViewModel.walletLog(null,
        page: goPage, type: widget.model.typeForServer);
    if (value.data == null) {
      setLoadOk();
      return;
    }
    if (goPage == 1) {
      dataList = value.data;
    } else {
      dataList.addAll(value.data);
    }
    if (value.data!.isEmpty || value.data!.length < PageMini.perPage) {
      hasNextPage = false;
      refreshController.loadNoData();
    }
    setLoadOk();
  }

  /*
  * 刷新处理
  * */
  Future refreshHandle() async {
    goPage = 1;
    await getData();
    refreshController.refreshCompleted();
  }

  /*
  * 加载处理
  * */
  Future loadingHandle() async {
    goPage++;
    await getData();
    refreshController.loadComplete();
  }

  @override
  Widget build(BuildContext context) {
    return MySmartRefresh(
      controller: refreshController,
      onRefresh: () async {
        return refreshHandle();
      },
      onLoading: () async {
        return loadingHandle();
      },
      child: () {
        if (!isLoadOk) {
          return const LoadingView();
        }
        if (!listNoEmpty(dataList)) {
          return NoDataView();
        }
        return ListView.builder(
          padding: EdgeInsets.symmetric(vertical: 10.px),
          itemCount: dataList.length,
          itemBuilder: (context, index) {
            final item = dataList[index];
            final BillTypeFromEnum billType = item.type == 2
                ? BillTypeFromEnum.recharge
                : item.type == 3
                    ? BillTypeFromEnum.withdraw
                    : BillTypeFromEnum.transfers;
            final typeStr = item.remark ?? "unknown".tr;
            return InkwellWithOutColor(
              child: Container(
                padding:
                    EdgeInsets.symmetric(vertical: 10.px, horizontal: 15.px),
                margin: EdgeInsets.symmetric(horizontal: 15.px, vertical: 5.px),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.all(
                    Radius.circular(10.px),
                  ),
                ),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(
                                typeStr,
                                style: TextStyle(
                                  color: Color(0xff000000),
                                  fontWeight: MyFontWeight.bold,
                                  fontSize: 16.px,
                                ),
                              ),
                              SizedBox(height: 5.px),
                              Text(
                                '${'interactionTime'.tr}:${MyDate.formatTimeStampParse(item.createTime ?? 0)}',
                                style: hintStyle,
                              ),
                              SizedBox(height: 5.px),
                            ],
                          ),
                        ),
                        Column(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          children: [
                            () {
                              final numberColor =
                                  billType == BillTypeFromEnum.recharge
                                      ? 0xff000000
                                      : 0xffFF2722;
                              return Row(
                                children: [
                                  // Text(
                                  //   '${billType == BillType.charge ? "+" : "-"}${billType != BillType.transform ? "\$" : ""}',
                                  //   style: TextStyle(
                                  //     color: Color(numberColor),
                                  //     fontSize: 16.px,
                                  //     fontWeight: MyFontWeight.bold,
                                  //   ),
                                  // ),
                                  Padding(
                                    padding: EdgeInsets.only(top: 20.px),
                                    child: Text(
                                      () {
                                        final showU =
                                            item.count.toString().endsWith("U");
                                        final uStr = showU ? "" : "U";
                                        if (item.type == 7) {
                                          return "${item.count}$uStr";
                                        }
                                        return '${(item.count?.startsWith('-') ?? false) ? "" : (item.count?.startsWith('+') ?? false) ? "" : "+"}${item.count}$uStr';
                                        // ${billType != BillType.transform ? "" : "U"}
                                      }(),
                                      style: TextStyle(
                                        color: Color(numberColor),
                                        fontSize: 20.px,
                                        fontWeight: MyFontWeight.bold,
                                      ),
                                    ),
                                  )
                                ],
                              );
                            }(),
                            SizedBox(height: 4.px),
                            Text(
                              '${'greenPoints'.tr}:${item.balance}',
                              style: TextStyle(
                                color: Color(0xff999999),
                                fontSize: 12.px,
                                fontWeight: MyFontWeight.medium,
                              ),
                            )
                            // Text(
                            //   index.isEven ? '$typeStr中' : "已完成",
                            //   style: TextStyle(
                            //     color: index.isEven
                            //         ? Color(0xff999999)
                            //         : MyTheme.mainColor.value,
                            //     fontSize: 12.px,
                            //     fontWeight: MyFontWeight.medium,
                            //   ),
                            // )
                          ],
                        )
                      ],
                    ),
                    Row(
                      children: [
                        Text(
                          item.type == 4
                              ? () {
                                  if (item.count?.startsWith('-') ?? false) {
                                    return '${"transferType".tr}:${hidePhoneUserNewMark(Q1Data.phone)}->${hidePhoneUserNewMark(item.phone)}';
                                  }
                                  return '${"transferType".tr}:${hidePhoneUserNewMark(item.phone)}->${hidePhoneUserNewMark(Q1Data.phone)}';
                                }()
                              : '${'serialNumber'.tr}:${item.id}',
                          style: hintStyle,
                        ),
                        if (billType != BillTypeFromEnum.transfers)
                          SizedBox(width: 2.px),
                        if (billType != BillTypeFromEnum.transfers)
                          Image.asset(
                            'assets/images/mine/ic_bill_copy.png',
                            width: 12.px,
                            height: 12.px,
                          )
                      ],
                    )
                  ],
                ),
              ),
              onTap: () {
                if (billType == BillTypeFromEnum.transfers) {
                  return;
                }
                copyText("${item.id}");
              },
            );
          },
        );
      }(),
    );
  }

  @override
  void update([List<Object>? ids, bool condition = true]) {
    setState(() {});
  }
}
